package com.cloud.handlerWritingOpenfeign;

import lombok.Data;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

@Data
@Component
public class FeignInvocationHandler<T> implements InvocationHandler {
    public FindMapping.PackDetails res;
    public Class<T> tClass;

    public FeignInvocationHandler() {
    }

    public FeignInvocationHandler(FindMapping.PackDetails res, Class<T> tClass) {
        this.res = res;
        this.tClass = tClass;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
        RestTemplate restTemplate = SpringBeanUtil.getBean("restTemplate", RestTemplate.class);

        // 获取服务名
        HandWritFeignAnnotation annotation = method.getDeclaringClass().getAnnotation(HandWritFeignAnnotation.class);

        String serviceName = annotation.value();
        //根据服务名使用DiscoverClient找到  对应ip
        String ip = "127.0.0.1:8080";
        //获取请求参数做拼接
        RequestMapping getMapping = method.getDeclaredAnnotation(RequestMapping.class);
        if (getMapping == null) {
            throw new Exception("getMapping is null");
        }
        String[] requestName = getMapping.value();
        String requestUrl = "http://" + ip + requestName[0];
//        restTemplate
        ResponseEntity<?> result = restTemplate.getForEntity(requestUrl, method.getReturnType());
        result.getBody();
        return result.getBody();
    }
}
